package net.woggle.shackbrowseapi;

import java.io.IOException;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

public class MyResponseHandler implements ResponseHandler<String> {
	BasicClientCookie[] cookie;
	int num = 0;
	public String handleResponse(final HttpResponse response)
	            throws HttpResponseException, IOException {
	        StatusLine statusLine = response.getStatusLine();
	        HttpEntity entity = response.getEntity();
	        
	        Header[] hs = response.getHeaders("Set-Cookie");
	        num = hs.length;
	        if (num > 0)
	        {
	        	cookie = new BasicClientCookie[num];
	        	for (int i = 0; i < num; i++)
	        	{
	        		cookie[i] = parseRawCookie(hs[i].getValue());
	        	}
	        }
	        if (statusLine.getStatusCode() >= 300) {
	            EntityUtils.consume(entity);
	            throw new HttpResponseException(statusLine.getStatusCode(),
	                    statusLine.getReasonPhrase());
	    }
	    return entity == null ? null : EntityUtils.toString(entity, HTTP.UTF_8);
	}
	
	BasicClientCookie parseRawCookie(String rawCookie) {
		int start = rawCookie.indexOf("_shack_li_=") + "_shack_li_=".length();
		int end = rawCookie.indexOf(";", start);
	    String cookieValue = rawCookie.substring(start, end);
	    String cookieName = "_shack_li_";
	    
	    BasicClientCookie cookie = new BasicClientCookie(cookieName, cookieValue);

	    return cookie;
	}
}